package com.yimixian.app.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.ta.utdid2.android.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.EventBusDomain.HomeDataLocatedStatus;
import com.yimixian.app.EventBusDomain.OrderListPointTab;
import com.yimixian.app.EventBusDomain.PlusMinusIconMessage;
import com.yimixian.app.EventBusDomain.ShowAdSelectChange;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.activity.BaseNaviFragmentGroupActivity;
import com.yimixian.app.activity.YMXMainActivity;
import com.yimixian.app.adapter.HomeListViewAdapter;
import com.yimixian.app.address.ChooseAddressOrStoreActivity;
import com.yimixian.app.address.ShortAddress;
import com.yimixian.app.address.ShowAddressesActivity;
import com.yimixian.app.address.SwitchAddressActivity;
import com.yimixian.app.cart.CartManager;
import com.yimixian.app.cart.GoodsItemPresenter;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.SharePreferenceKeys;
import com.yimixian.app.common.StatConstants;
import com.yimixian.app.common.StopNoticeActivity;
import com.yimixian.app.common.UMengConstants;
import com.yimixian.app.common.WebViewActivity;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.location.LocatedListener;
import com.yimixian.app.location.LocationProvider;
import com.yimixian.app.model.Address;
import com.yimixian.app.model.AdvertInfo;
import com.yimixian.app.model.AppConfig;
import com.yimixian.app.model.Banner;
import com.yimixian.app.model.CartUpdate;
import com.yimixian.app.model.HeadInfo;
import com.yimixian.app.model.HomeDataBean;
import com.yimixian.app.model.ImageInfo;
import com.yimixian.app.model.KV;
import com.yimixian.app.model.Material;
import com.yimixian.app.model.PullMessage;
import com.yimixian.app.model.SortGoodsItem;
import com.yimixian.app.model.Store;
import com.yimixian.app.model.User;
import com.yimixian.app.net.HttpApi;
import com.yimixian.app.rest.YmxDataService;
import com.yimixian.app.rest.api.CartUpdateAPI;
import com.yimixian.app.rest.api.ClearRedPointAPI;
import com.yimixian.app.rest.api.GetRedPointAPI;
import com.yimixian.app.rest.api.HomeDataAPI;
import com.yimixian.app.rest.api.ResponseDataTypeAPI;
import com.yimixian.app.search.SearchActivity;
import com.yimixian.app.ui.AutoScrollTextView;
import com.yimixian.app.ui.HomeHeadView;
import com.yimixian.app.ui.MyTextView;
import com.yimixian.app.ui.ParabolaView;
import com.yimixian.app.ui.PinnedSectionListView;
import com.yimixian.app.ui.PullMessageView;
import com.yimixian.app.ui.dialog.HomeAdDialog;
import com.yimixian.app.ui.pull.PullRefreshLayout;
import com.yimixian.app.util.DateUtil;
import com.yimixian.app.util.PaoWuXianAnimTool;
import com.yimixian.app.util.PaoWuXianAnimator;
import com.yimixian.app.util.ServiceUtils;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.Strings;
import com.yimixian.app.util.UiUtils;
import com.ymx.sdk.util.DeviceUtils;
import com.ymx.sdk.widget.PullToRefreshView.PullToRefreshBase;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import retrofit.client.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * 首页
 */
public class HomeFragment extends DialogGoodDetailFragment implements
        PullToRefreshBase.OnRefreshListener2<ListView>, GoodsItemPresenter.OnPlusButtonClickListener,
        HomeHeadView.OnHeadViewClickListener, View.OnClickListener, ServiceUtils.CountDownDataListener{

    private View mRootView;
    public String adUrl;
    ImageButton toTopBtn;
    FrameLayout mMainFrame;
    HomeListViewAdapter mHomeListViewAdapter;
    HomeHeadView headView;
    LinearLayout mLoadingView;
    LinearLayout mCannotDeliverView;
    LinearLayout mLocatingFailedView, linMarquee;
    FrameLayout mPullMessageFrame;
    RelativeLayout mContentFrame;
    TextView mLoadingText;
    TextView mFetchMethodText;
    TextView mAddressText;
    ImageView iv_address;
    ImageView iv_right_arrow;
    TextView mCannotDeliverText;
    MyTextView textMarquee;
    public AutoScrollTextView text_marquee_hight;
    TextView textMore;
    TextView mShowDeliveryZoneButton;
    LinearLayout mTopBar;
    ImageView deleteImg, marquee_left;
    Button selfLocatedBtn, reLoadMoreBtn;
    private VelocityTracker velocityTracker;//速度跟踪

    private boolean isClickGoTopBtn = false;
    private boolean isTouchScroll = false;
    public static boolean needLoadImage = true;
    private boolean scrollFlag = false;// 标记是否滑动
    private int lastVisibleItemPosition = 0;// 标记上次滑动位置
//    PinnedSectionListView mPinnedSectionListView;
    ListView mPinnedSectionListView;
    PullRefreshLayout layout;

    private ClearRedPointAPI mClearRedPointAPI;
    boolean isAddressChange;
    HomeDataBean homeDataBean;
    private boolean isNeedGetCart = true;
    private PlusMinusIconMessage mPlusMinusIconMessage;
    private int mCurrentGoodsItemId;
    private HomeDataAPI mHomeDataAPI;
    private boolean mIsCreated = false;
    private Address mCurrentAddress;
    private YmxDataService mYmxDataService;
    private SharedPreferences mSharedPreferences;
    private DataManager mDataManager;
    private CartManager mCartManager;
    private boolean mIsPullMessageChecked;
    Handler mHandler = new Handler();
    private GetRedPointAPI mGetRedPointAPI;
    private List<SortGoodsItem> mList;
    private int scrollIndex = 0;
    PullMessageView pullMessageView;
    private ImageView iv_send;
    private Dialog tipDialog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        if (mIsCreated && mRootView != null) {
            return mRootView;
        }
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().registerSticky(this);
        }
        setupMemberVariables();
        mRootView = initView(container, inflater);
        mIsCreated = true;
        getUserInfo(false);
        headView = new HomeHeadView(getActivity());
        headView.setOnHeadViewClickListener(this);
        mHomeListViewAdapter = new HomeListViewAdapter(getActivity(), mList, this);
        mHomeListViewAdapter.setMLastPosition(scrollIndex);
        layout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //刷新时间至少0.8秒
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS) == null) {
                            isNeedGetCart = true;
                            startLocatingCurrentAddress();
                        } else {
                            isNeedGetCart = false;
                            getJiShiSonData(false);
                        }
                    }
                }, 800);
            }
            });
        layout.setRefreshStyle(PullRefreshLayout.YMX_PULL_DRAWABLE);
        mPinnedSectionListView.addHeaderView(headView);
        mPinnedSectionListView.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    // 当不滚动时
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:// 是当屏幕停止滚动时
//                        if(isClickGoTopBtn){
//                            if(mPinnedSectionListView.getFirstVisiblePosition() == 0){
//                                headView.getScrollPlayView().setIsPause(false);
//                                needLoadImage = true;
//                                isClickGoTopBtn = false;
//                            }
//                        }else if(isTouchScroll){
//                            needLoadImage = true;
//                        }
//                        mHomeListViewAdapter.notifyDataSetInvalidated();
//                        mHomeListViewAdapter.notifyDataSetChanged();
                        scrollFlag = false;
                        //                        // 判断滚动到底部
                        //                        if (mPinnedSectionListView.getLastVisiblePosition() == (listView
                        //                                .getCount() - 1)) {
                        //                            toTopBtn.setVisibility(View.VISIBLE);
                        //                        }
                        //                        // 判断滚动到顶部
                        //                        if (mPinnedSectionListView.getFirstVisiblePosition() == 0) {
                        //                            toTopBtn.setVisibility(View.GONE);
                        //                        }
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:// 滚动时
                        scrollFlag = true;
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING:// 是当用户由于之前划动屏幕并抬起手指，屏幕产生惯性滑动时
                        scrollFlag = false;
                        break;
                }
                if (mHomeListViewAdapter != null && scrollState == 0)
                    mHomeListViewAdapter.isScrollUp(0);
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                // 当开始滑动且ListView底部的Y轴点超出屏幕最大范围时，显示或隐藏顶部按钮
                toTopBtn.setVisibility(firstVisibleItem > 1 ? View.VISIBLE : View.GONE);
                if (scrollFlag) {
                    if (firstVisibleItem > lastVisibleItemPosition) {// 上滑
                        if (mHomeListViewAdapter != null)
                            mHomeListViewAdapter.isScrollUp(1);
                    } else if (firstVisibleItem < lastVisibleItemPosition) {// 下滑
                        if (mHomeListViewAdapter != null)
                            mHomeListViewAdapter.isScrollUp(-1);
                    } else {
                        return;
                    }
                    lastVisibleItemPosition = firstVisibleItem;
                }
            }
        });

        // 添加footerview
        LinearLayout footerView = (LinearLayout) LayoutInflater.from(getActivity()).inflate(
                R.layout.home_footer_view, null);
        textMore = (TextView) footerView.findViewById(R.id.text_more);
        textMore.setOnClickListener(this);
        mPinnedSectionListView.setAdapter(mHomeListViewAdapter);
        mPinnedSectionListView.addFooterView(footerView);
        mHomeListViewAdapter.mListView = mPinnedSectionListView;
        return mRootView;
    }

    private View initView(ViewGroup container, LayoutInflater inflater) {
        View rootView = inflater.inflate(R.layout.home_new_activity, container, false);
        mLoadingView = (LinearLayout) rootView.findViewById(R.id.loading_view);
        mCannotDeliverView = (LinearLayout) rootView.findViewById(R.id.cannot_deliver_view);
        mLocatingFailedView = (LinearLayout) rootView.findViewById(R.id.locating_failed_view);
        linMarquee = (LinearLayout) rootView.findViewById(R.id.lin_marquee);
        mContentFrame = (RelativeLayout) rootView.findViewById(R.id.content_frame);
        mLoadingText = (TextView) rootView.findViewById(R.id.loading_text);
        mFetchMethodText = (TextView) rootView.findViewById(R.id.fetch_method_text);
        mAddressText = (TextView) rootView.findViewById(R.id.address_text);
        iv_address = (ImageView) rootView.findViewById(R.id.iv_address);
        iv_right_arrow = (ImageView) rootView.findViewById(R.id.iv_right_arrow);
        mPullMessageFrame = (FrameLayout) rootView.findViewById(R.id.pull_message_frame);
        text_marquee_hight = (AutoScrollTextView) rootView.findViewById(R.id.text_marquee_hight);
        deleteImg = (ImageView) rootView.findViewById(R.id.delete_img);
        marquee_left = (ImageView) rootView.findViewById(R.id.marquee_left);
        mCannotDeliverText = (TextView) rootView.findViewById(R.id.cannot_deliver_text);
        textMarquee = (MyTextView) rootView.findViewById(R.id.text_marquee);
        mShowDeliveryZoneButton = (TextView) rootView.findViewById(R.id.show_delivery_zone_button);
        mTopBar = (LinearLayout) rootView.findViewById(R.id.ll_top_bar);
        iv_send = (ImageView) rootView.findViewById(R.id.iv_send);
        toTopBtn = (ImageButton) rootView.findViewById(R.id.to_top_btn);
        mMainFrame = (FrameLayout) rootView.findViewById(R.id.main_frame);
        selfLocatedBtn = (Button) rootView.findViewById(R.id.self_located_btn);
        reLoadMoreBtn = (Button) rootView.findViewById(R.id.load_more_btn);
        deleteImg.setOnClickListener(this);
        reLoadMoreBtn.setOnClickListener(this);
        selfLocatedBtn.setOnClickListener(this);
//        mPinnedSectionListView = (PinnedSectionListView) rootView.findViewById(R.id.list_view);
        mPinnedSectionListView = (ListView) rootView.findViewById(R.id.list_view);
        layout = (PullRefreshLayout) rootView.findViewById(R.id.swipeRefreshLayout);
        RelativeLayout search = (RelativeLayout) rootView.findViewById(R.id.rl_search);
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(UiUtils.isFastDoubleClick()) {
                    return ;
                }
                if(isAdded()) {
                    MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                            UMengConstants.NEW_HOME_SEARCH_BTN);
                    Intent intent = SearchActivity.buildIntent(getActivity());
                    startActivityForResult(intent, 0);
                    getActivity().overridePendingTransition(R.anim.slide_in_from_right, 0);
                }
            }
        });

        if (getActivity() instanceof YMXMainActivity) {
           // this.mCartTab = (CartRadioButton) ((YMXMainActivity) getActivity()).mCartTab;
            CartManager.getInstance().setCartQuantityTextView(
                    ((YMXMainActivity) getActivity()).mCartContent);
        }
        mTopBar.setOnClickListener(this);
        toTopBtn.setOnClickListener(this);
        return rootView;
    }

    public float getViewWidthForMarquee(View view){
        if (view == null) return 0;
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        return view.getMeasuredHeight();
    }

    public void comeBackUpdateMarquee(){
        if (homeDataBean == null) return;
        if (!StringUtils.isEmpty(homeDataBean.storeNotice)){
            if (UiUtils.isNeedNotice(String.valueOf(homeDataBean.id)) &&
                    mHandler != null && text_marquee_hight != null){
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        text_marquee_hight.startScroll();
                    }
                }, 100);

            }else{
                if (text_marquee_hight != null) text_marquee_hight.stopScroll();
            }
        }
    }



    @Override
    public void onResume() {
        super.onResume();
        if(canPullMessageShow){
            if(null!=pullMessage&&!mIsPullMessageChecked)dealPullMessage(pullMessage);
            canPullMessageShow = false;
        }
        if (getActivity() != null && ((YMXMainActivity) getActivity()).mSessionFragment == null){
            comeBackUpdateMarquee();
            //分类页面提示刷新
            if (isAdded() && ((YMXMainActivity)getActivity()).isHomeFlush){
                ((YMXMainActivity)getActivity()).isHomeFlush = false;
                getUserInfo(false);
            }else{
                if (UiUtils.isNeedFlush(this)){
                    getUserInfo(false);
                }else{
                    CartManager.getInstance().setSortSections(mList);
                    mHomeListViewAdapter.setList(mList);
                    UiUtils.updateCartDescription(getActivity(), Constants.PageType.HOME);
                }
            }
        }
    }

    private void setupMemberVariables() {
        mDataManager = DataManager.getInstance();
        mSharedPreferences = getActivity().getSharedPreferences(Constants.SHARED_PREFS_NAME,
                Context.MODE_PRIVATE);
        mYmxDataService = YmxDataService.getInstance();
//        mLocationProvider = new LocationProvider(getActivity());
//        mBaiduGeoCoder = GeoCoder.newInstance();
        mCartManager = CartManager.getInstance();
    }

    private void fetchData() {
        mYmxDataService.getAppConfig(true)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Action1<AppConfig>() {
                            @Override
                            public void call(AppConfig appConfig) {

                                if (mDataManager.get(CacheKeys.TOKEN) != null) {

                                    if (SharedPreferencesHelper
                                            .getBoolean(Constants.ISUPDATEORDERTABRPOINT)) {
                                        fetchData(true, GetRedPointAPI.GETREDURL);
                                    }
                                    checkAndDealPullMessage();
                                    Address address = SharedPreferencesHelper
                                            .getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
                                    if (address != null && address.isPickup) {
                                        EventBus.getDefault().postSticky(new HomeDataLocatedStatus(Constants.LocatedType.LOCATED_SUCCESS));
                                        getJiShiSonData(true);
                                    } else {
                                        fetchUserAndAddresses();
                                    }
                                } else {
                                    startLocatingCurrentAddress();
                                }

                                try {
                                    if ("true".equalsIgnoreCase(appConfig.maintenance.status)) {
                                        Intent intent = new Intent(getActivity(), StopNoticeActivity.class);
                                        intent.putExtra("etime", appConfig.maintenance.etime);
                                        intent.putExtra("ntime", appConfig.maintenance.ntime);
                                        startActivityForResult(intent, 10001);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                                String version = appConfig.regions_version;
                                String regionUrl = "http://api.1mxian.com/v5/app_config/regions.json";
                                String oldVersion = SharedPreferencesHelper.getString(Constants.REGION_VERION);
                                String regionData = SharedPreferencesHelper.getString(Constants.REGION_DATA);
                                if (Strings.isNullOrEmpty(version) || !version.equals(oldVersion) || Strings.isNullOrEmpty(oldVersion)) {
                                    SharedPreferencesHelper.commitString(Constants.REGION_VERION, version);
                                    if (!Strings.isNullOrEmpty(appConfig.regions_url)) {
                                        regionUrl = appConfig.regions_url;
                                    }
                                    HttpApi.startGetRequest(regionUrl, null, new HttpApi.RequestCallBack() {

                                        @Override
                                        public void requestSuccess(String result) {
                                            SharedPreferencesHelper.commitString(Constants.REGION_DATA, result);
                                            System.out.println("哈利路亚保存成功***" + result);
                                        }

                                        @Override
                                        public void requestError() {
                                        }

                                        @Override
                                        public void alwaysDo() {
                                        }
                                    });
                                }

                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                UiUtils.toastError(
                                        SystemFramework.getInstance().getGlobalContext(),
                                        throwable);
                                showFetchDataErrorUi();
                                EventBus.getDefault().postSticky(new HomeDataLocatedStatus(Constants.LocatedType.LOCATED_FAILED));
                            }
                        });
    }

    /**
     * 获取用户信息
     */
    private void getUserInfo(boolean isUseCurrentUserCache){
        showLoadingView(UiUtils.getSafeActivity(this).getResources()
                .getString(R.string.loading));
        final String token = mDataManager.get(CacheKeys.TOKEN);
        User user = mDataManager.<User> get(CacheKeys.CURRENT_USER);
        if (token != null && user == null){
            mYmxDataService.getCurrentUser(isUseCurrentUserCache)
                    .observeOn(AndroidSchedulers.mainThread()).
                    subscribe(new Action1<User>() {
                        @Override
                        public void call(User user) {
                            if (user != null) {
                                fetchData();
                            }else{
                                mDataManager.remove(CacheKeys.TOKEN);
                                SharedPreferencesHelper.clearUser(SharePreferenceKeys.CURRENT_USER);
                                fetchData();
                            }
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            fetchData();
                            //                        UiUtils.toastError(getActivity(), throwable);
                        }
                    });
        }else{
            fetchData();
        }
    }


    private void fetchUserAndAddresses() {
        mYmxDataService.getAddresses(false)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Action1<List<Address>>() {
                            @Override
                            public void call(List<Address> addresses) {
                                SharedPreferencesHelper.saveAddresses((ArrayList) addresses,
                                        SharePreferenceKeys.ADDRESSES);
                                Address mAddress = SharedPreferencesHelper
                                        .getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
                                int addressId;
                                if (mAddress == null || mAddress.id == 0) {
                                    startLocatingCurrentAddress();
                                    return;
                                }
                                addressId = mAddress.id;
                                for (Address address : addresses) {
                                    if (address.id == addressId) {
                                        SharedPreferencesHelper.saveAddress(address,
                                                SharePreferenceKeys.CURRENT_ADDRESS);
                                        getJiShiSonData(true);
                                        EventBus.getDefault().postSticky(new HomeDataLocatedStatus(Constants.LocatedType.LOCATED_SUCCESS));
                                        return;
                                    }
                                }
                                SharedPreferencesHelper
                                        .clearAddress(SharePreferenceKeys.CURRENT_ADDRESS);
                                startLocatingCurrentAddress();
                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                if (isAdded()) {
                                    UiUtils.toastError(
                                            SystemFramework.getInstance().getGlobalContext(),
                                            throwable);
                                    showFetchDataErrorUi();
                                    EventBus.getDefault().postSticky(new HomeDataLocatedStatus(Constants.LocatedType.LOCATED_FAILED));
                                }
                            }
                        });
    }

    private void showLoadingView(String loadingText) {
        if (mContentFrame == null)
            return;
        mContentFrame.setVisibility(View.INVISIBLE);
        mLoadingView.setVisibility(View.VISIBLE);
        mLoadingText.setText(loadingText);
        mCannotDeliverView.setVisibility(View.GONE);
        mLocatingFailedView.setVisibility(View.GONE);
    }

    private void startLocatingCurrentAddress(){
        Address noLoginAddress = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_NO_LOGIN_ADDRESS);
        if(noLoginAddress == null || noLoginAddress.id == -1){
            LocationProvider.getInstance().startBaiduLocated(true, new LocatedListener() {
                @Override
                public void locatedSuccessGeoPoiInfoListener(PoiInfo poiInfo) {
                    ShortAddress shortAddress = new ShortAddress(poiInfo,
                            poiInfo.location);
                    SharedPreferencesHelper.saveAddress(shortAddress,
                            SharePreferenceKeys.CURRENT_ADDRESS);
                    EventBus.getDefault().postSticky(new HomeDataLocatedStatus(Constants.LocatedType.LOCATED_SUCCESS));
                    checkAndDealPullMessage();
                    getJiShiSonData(poiInfo.location.longitude + "", poiInfo.location.latitude + "", true);
                }

                @Override
                public void locatedFailedGeoPoiInfoListener() {
                    EventBus.getDefault().postSticky(new HomeDataLocatedStatus(Constants.LocatedType.LOCATED_FAILED));
                    showLocatingFailedUi();
                }

                @Override
                public void locatedSuccessListener(BDLocation location) {
                }

                @Override
                public void locatedFailedListener() {
                    EventBus.getDefault().postSticky(new HomeDataLocatedStatus(Constants.LocatedType.LOCATED_FAILED));
                    showLocatingFailedUi();
                }
            });
        }else{
            getJiShiSonData(false);
        }
    }

    private void fetchNormalStore(boolean showLoadingView) {
        if (showLoadingView) {
            if (isAdded()) {
                showLoadingView(getString(R.string.loading));
            }
        }
        Address address = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
        mCurrentAddress = address;
        // 区分自提还是配送
        mFetchMethodText.setText(mCurrentAddress.isPickup ? UiUtils.getSafeActivity(this).getResources()
                .getString(R.string.pick_up_self)
                : UiUtils.getSafeActivity(this).getResources()
                .getString(R.string.send_to));
        setmAddressText(address);
        mAddressText.setVisibility(View.VISIBLE);
//        iv_address.setVisibility(View.VISIBLE);
//        mFetchMethodText.setVisibility(View.GONE);
        fetchData(true, HomeDataAPI.HOMEDATAURL);
    }

    private void setIcon(String result){
        JSONObject json = null;
        try {
            json = new JSONObject(result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (json != null) {
            String type = json.optString("delivery_img");
            String tip = "";
            iv_send.setVisibility(View.VISIBLE);
            iv_address.setVisibility(View.VISIBLE);
            mFetchMethodText.setVisibility(View.GONE);
            iv_right_arrow.setVisibility(View.VISIBLE);
            if (Strings.isNullOrEmpty(type)) {//配送至
                iv_send.setVisibility(View.GONE);
                mFetchMethodText.setVisibility(View.VISIBLE);
                mFetchMethodText.setText(UiUtils.getSafeActivity(HomeFragment.this).getResources()
                        .getString(R.string.send_to));
                iv_address.setVisibility(View.GONE);
            } else if ("delivery_zt".equals(type)) {//自提
                iv_send.setImageResource(R.drawable.icon_address_self);
                if (Strings.isNullOrEmpty(mCurrentAddress.poiName)) {
                    tip = "该地区支持自提服务，下单后请您于次日到" + mCurrentAddress.poiAddress + "领取您的订单";
                } else {
                    tip = "该地区支持自提服务，下单后请您于次日到" + mCurrentAddress.poiName + "领取您的订单";
                }
            } else if ("delivery_jss_crd".equals(type)) {//及时送(59分钟达)和次日达
                iv_send.setImageResource(R.drawable.icon_address_59_and_next);
                tip = "该地区支持次日达及59分达服务。59分达商品将于您下单后59分内送达，次日达商品将于您下单后次日送达";
            } else if ("delivery_jss".equals(type)) {//及时送(59分钟达)
                iv_send.setImageResource(R.drawable.icon_address_59);
                tip = "该地区支持59分达服务，您的订单将于下单后59分内送达";
            } else if ("delivery_crd".equals(type)) {//次日达
                iv_send.setImageResource(R.drawable.icon_address_next);
                tip = "该地区支持次日达服务，您的订单将于下单后次日送达";
            } else if (type != null && type.startsWith("http")) {
                Picasso.with(getContext()).load(type).into(iv_send);
            }
            if (!Strings.isNullOrEmpty(tip)) {
                final String message = tip;
                iv_send.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        tipDialog = UiUtils.showOKDialog(getContext(), message, "知道了", new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                if (tipDialog != null)
//                                    tipDialog.dismiss();
//                            }
//                        });
                        mTopBar.performClick();
                    }
                });
                TranslateAnimation trans = new TranslateAnimation(
                        Animation.RELATIVE_TO_SELF, -1.0f,Animation.RELATIVE_TO_SELF, 0f,
                        Animation.RELATIVE_TO_SELF, 0f,Animation.RELATIVE_TO_SELF, 0f);
                trans.setDuration(300);
                trans.setStartOffset(300);
                iv_send.startAnimation(trans);
            }
        }
    }

    private void setmAddressText(Address address){
        String text = "";
        //无poi点, 手动输入显示的地址
        if(Strings.isNullOrEmpty(address.poiName)){
            if(!Strings.isNullOrEmpty(address.poiAddress)){
                if(address.poiAddress.length() <= Constants.HOME_TITLE_MAX_LENGTH){
                    text = address.poiAddress;
                }else{
                    text = address.poiAddress.substring(0, Constants.HOME_TITLE_MAX_LENGTH) + "...";
                }
            }
        }else{
            if(!Strings.isNullOrEmpty(address.poiName)){
                if(address.poiName.length() <= Constants.HOME_TITLE_MAX_LENGTH){
                    text = address.poiName;
                }else{
                    text = address.poiName.substring(0, Constants.HOME_TITLE_MAX_LENGTH) + "...";
                }
            }
        }
        mAddressText.setText(text);
    }

    private void getJiShiSonData(final boolean showLoading) {
        getJiShiSonData(showLoading, null);
    }

    private void getJiShiSonData(final boolean showLoading, Address add) {
        if(add == null){
            Address address = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
            mCurrentAddress = address;
        }else{
            mCurrentAddress = add;
        }
        setmAddressText(mCurrentAddress);
        mAddressText.setVisibility(View.VISIBLE);
        iv_address.setVisibility(View.VISIBLE);
        iv_right_arrow.setVisibility(View.VISIBLE);
        mFetchMethodText.setVisibility(View.GONE);
        iv_send.setVisibility(View.GONE);
        getJiShiSonData(mCurrentAddress.longitude, mCurrentAddress.latitude, showLoading);
    }

    private void getJiShiSonData(String longitude, String latitude, final boolean showLoading) {
        if(mCurrentAddress != null && mCurrentAddress.id != 0){
            getJiShiSonDataNotPOI(mCurrentAddress.id + "", showLoading);
            return;
        }
        if (showLoading) {
            if (isAdded()) {
                showLoadingView(getString(R.string.loading));
            }
        }
        iv_send.setVisibility(View.GONE);
        Map<String, String> map = new HashMap<>();
        map.put("longitude", longitude);
        map.put("latitude", latitude);
        map.put("coord_system", Constants.BAIDU_COORD_SYSTEM);
        HttpApi.startGetRequest("/stores/store_info", map, new HttpApi.RequestCallBack() {
            @Override
            public void requestSuccess(String result) {
                setIcon(result);
            }

            @Override
            public void requestError() {

            }

            @Override
            public void alwaysDo() {
                fetchNormalStore(showLoading);
            }
        });
    }

    private void getJiShiSonDataNotPOI(String storeId, final boolean showLoading) {
        if (showLoading) {
            if (isAdded()) {
                showLoadingView(getString(R.string.loading));
            }
        }
        iv_send.setVisibility(View.GONE);
        Map<String, String> map = new HashMap<>();
        map.put("address_id", storeId);
        HttpApi.startGetRequest("/stores/store_info", map, new HttpApi.RequestCallBack() {
            @Override
            public void requestSuccess(String result) {
                setIcon(result);
            }

            @Override
            public void requestError() {

            }

            @Override
            public void alwaysDo() {
                fetchNormalStore(showLoading);
            }
        });
    }

    private void showFetchDataErrorUi() {
        DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case DialogInterface.BUTTON_NEUTRAL:
                        MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                                StatConstants.HOME_FETCH_DATA_ERROR_CLICK);
                        fetchData();
                        break;
                }
            }
        };

        if (isAdded()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
                    .setMessage(UiUtils.getSafeActivity(this).getResources()
                        .getString(R.string.network_error_try_again))
                    .setNeutralButton(UiUtils.getSafeActivity(this).getResources()
                        .getString(R.string.retry), dialogClickListener)
                    .setCancelable(false);
            UiUtils.showAlertDialog(builder);
        }
    }

    private void showLocatingFailedUi() {
        if (mLocatingFailedView == null) {
            return;
        }
        mLocatingFailedView.setVisibility(View.VISIBLE);
        mContentFrame.setVisibility(View.INVISIBLE);
        mLoadingView.setVisibility(View.GONE);
        mCannotDeliverView.setVisibility(View.GONE);
        mAddressText.setText(UiUtils.getSafeActivity(this).getResources()
                .getString(R.string.manual_choose_address));
        mAddressText.setVisibility(View.VISIBLE);
        iv_address.setVisibility(View.VISIBLE);
        mFetchMethodText.setVisibility(View.GONE);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (text_marquee_hight != null) text_marquee_hight.stopScroll();
    }

    @Override
    public void onStop() {
        super.onStop();
        layout.setRefreshing(false);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        super.onDetach();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mPlusMinusIconMessage = null;
    }

    // 下拉刷新
    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        if (SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS) == null) {
            isNeedGetCart = true;
            startLocatingCurrentAddress();
        } else {
            isNeedGetCart = false;
            getJiShiSonData(false);
        }
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
    }

    /**
     * 网络请求启动页广告图片
     */
    private void fetchAdInfoData(HomeDataBean store) {
        if (store == null) {
            return;
        }
        String installChannel = mDataManager.get(CacheKeys.INSTALL_CHANNEL);
        if (StringUtils.isEmpty(installChannel)) {
            try {
                installChannel = getActivity().getPackageManager()
                        .getApplicationInfo(
                                getActivity().getPackageName(),
                                PackageManager.GET_META_DATA).metaData
                                        .getString("UMENG_CHANNEL");
            } catch (PackageManager.NameNotFoundException ignored) {
            }
        }
        mYmxDataService.getAdInfo(store == null ? "" : store.regionId, installChannel)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<AdvertInfo>() {
            @Override
            public void call(AdvertInfo advertInfo) {
                if (advertInfo != null && !StringUtils.isEmpty(advertInfo.url))
                    dealAdInfo(advertInfo);
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                UiUtils.toastError(getActivity(), throwable);
            }
        });
    }

    /**
     * 处理启动页后面广告图逻辑
     */
    public void dealAdInfo(final AdvertInfo advertInfo) {
        Picasso picasso = Picasso.with(getActivity());
        picasso.load(advertInfo.url).into(new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                mDataManager.saveAdInfo(advertInfo);
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
                advertInfo.url = "";
                mDataManager.saveAdInfo(advertInfo);
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
                advertInfo.url = "";
                mDataManager.saveAdInfo(advertInfo);
            }
        });
    }

    private void showCannotDeliverView() {
        final Store store = SharedPreferencesHelper.getStore(SharePreferenceKeys.CURRENT_STORE);
        mContentFrame.setVisibility(View.INVISIBLE);
        mLoadingView.setVisibility(View.GONE);
        mLocatingFailedView.setVisibility(View.GONE);
        mCannotDeliverView.setVisibility(View.VISIBLE);
        iv_address.setVisibility(View.GONE);
        mFetchMethodText.setVisibility(View.VISIBLE);
        if (!Strings.isNullOrEmpty(store.cannotDeliverText)) {
            mCannotDeliverText.setText(store.cannotDeliverText);
        }
        if (Strings.isNullOrEmpty(store.deliveryZoneUrl)) {
            mShowDeliveryZoneButton.setVisibility(View.GONE);
        } else {
            mShowDeliveryZoneButton.setVisibility(View.VISIBLE);
            mShowDeliveryZoneButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MobclickAgent.onEvent(getActivity(), StatConstants.HOME_CANNOT_DELIVERY_CLICK);
                    Intent intent = new Intent(getActivity(), WebViewActivity.class);
                    intent.putExtra(WebViewActivity.EXTRA_URL, store.deliveryZoneUrl);
                    startActivity(intent);
                }
            });
        }
    }
    PullMessage pullMessage;
    public void checkAndDealPullMessage() {
        // 仅仅弹出一次PullMessage
        if (mIsPullMessageChecked) {
            return;
        }
        String token = mDataManager.get(CacheKeys.TOKEN);
        Address address = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
        Observable<PullMessage> pullMessageObservable = !TextUtils.isEmpty(token)
                ? mYmxDataService.getPullMessageByToken(token)
                : address != null ? mYmxDataService.getPullMessageByLocation(address.longitude,
                        address.latitude) : null;
        if (pullMessageObservable != null) {
            pullMessageObservable.observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                        new Action1<PullMessage>() {
                            @Override
                            public void call(final PullMessage pullMessage) {
                                HomeFragment.this.pullMessage = pullMessage;
                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                            }
                        });
        }

    }
    /**是否有推送消息弹框*/
    public boolean hasPullMessage(){
        return pullMessageView!=null;
    }
    private void dealPullMessage(final PullMessage pullMessage) {
        mIsPullMessageChecked = true;
        int id = mDataManager.get(CacheKeys.LAST_READ_PULL_MESSAGE_ID);
        if (pullMessage != null && !TextUtils.isEmpty(pullMessage.id) &&
                Integer.parseInt(pullMessage.id) > id) {
            mDataManager.put(CacheKeys.LAST_READ_PULL_MESSAGE_ID, Integer.parseInt(pullMessage.id));

            pullMessageView = new PullMessageView(getActivity());
            mPullMessageFrame.addView(pullMessageView);
            pullMessageView.bind(pullMessage, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPullMessageFrame.removeView(pullMessageView);
//                    showHomeAd(true);
                }
            }, !TextUtils.isEmpty(pullMessage.url) ? new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPullMessageFrame.removeView(pullMessageView);
//                    showHomeAd(true);
                    Intent intent = new Intent(getActivity(), WebViewActivity.class);
                    intent.putExtra(WebViewActivity.EXTRA_URL, pullMessage.url);
                    getActivity().startActivity(intent);
                }
            } : null);
        }
    }

    public void reFreshData() {
        // 判断是配送还是自提
        Address noLoginAddress = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_NO_LOGIN_ADDRESS);
        if (SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS) == null
                && (noLoginAddress == null || noLoginAddress.id == -1)) {
            startLocatingCurrentAddress();
        } else {
            getJiShiSonData(true);
        }
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.delete_img://删除通知
                linMarquee.setVisibility(View.GONE);
                if (text_marquee_hight != null) text_marquee_hight.stopScroll();
                if (homeDataBean != null)
                    SharedPreferencesHelper.commitLong(String.valueOf(homeDataBean.id),
                            System.currentTimeMillis());
                break;
            case R.id.load_more_btn://定位失败后重新拉取数据
                getUserInfo(false);
                break;
            case R.id.self_located_btn://定位失败后按钮点击事件
            case R.id.ll_top_bar://切换地址
                if(UiUtils.isFastDoubleClick()) {
                    return;
                }
                MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                        StatConstants.HOME_ADDRESS_HEADER_CLICK);
                if(DataManager.getInstance().get(CacheKeys.TOKEN) == null && !"请手动选择收货地址".equals(mAddressText.getText().toString())){
                    startActivityForResult(new Intent(getActivity(), SwitchAddressActivity.class), 0);
                }else{
                    startActivityForResult(
                            new Intent(getActivity(), ChooseAddressOrStoreActivity.class).putExtra(
                                    ShowAddressesActivity.EXTRA_MODE,
                                    ShowAddressesActivity.LOCATE_ADDRESS_MODE),
                            Constants.PICK_ADDRESS_REQUEST_CODE);
                }
                break;
            case R.id.to_top_btn://回滚到顶端
                needLoadImage = false;
                isClickGoTopBtn = true;
                isTouchScroll = false;
//                headView.getScrollPlayView().setIsPause(true);
                mPinnedSectionListView.smoothScrollToPositionFromTop(0, 0, 200);

                break;
            case R.id.text_more://点击查看全部商品
                if (isAdded()){
                    ((YMXMainActivity)getActivity()).switchTab(YMXMainActivity.TAB_KIND);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void OnHeadViewClick(Enum type, int position) {
        if (homeDataBean == null) return;
        if (type == Constants.HeadViewType.Banners) {
            Material<Banner> materialSliders = homeDataBean.dataMap.get(ResponseDataTypeAPI.HomeDataType.SLIDES);
            if (materialSliders != null && materialSliders.mList != null){
                Map<String, String> hashMap = new HashMap<>();
                hashMap.put("position",
                        String.valueOf(position));
                DateUtil.setCityUMeng(hashMap, UMengConstants.NEW_HOME_CAROUSELBANNER);
                Intent intent = new Intent(getContext(), WebViewActivity.class);
                intent.putExtra(WebViewActivity.EXTRA_URL,
                        materialSliders.mList.get(position).introUrl);
                intent.putExtra(WebViewActivity.STORE_ID,
                        homeDataBean == null ? "" : homeDataBean.id);
                startActivity(intent);
            }
        }
        if (type == Constants.HeadViewType.Metro) {
            Material<ImageInfo> materialMetros = homeDataBean.dataMap.get(ResponseDataTypeAPI.HomeDataType.METROS);
            if (materialMetros != null && materialMetros.mList != null){
                Map<String, String> hashMap = new HashMap<>();
                hashMap.put("position",
                        String.valueOf(position));
                DateUtil.setCityUMeng(hashMap, UMengConstants.NEW_HOME_METRO);
                Intent intent = new Intent(getContext(), WebViewActivity.class);
                intent.putExtra(WebViewActivity.EXTRA_URL,
                        materialMetros.mList.get(position).url);
                intent.putExtra(WebViewActivity.STORE_ID,
                        homeDataBean == null ? "" : homeDataBean.id);
                startActivity(intent);
            }
        }
        if (type == Constants.HeadViewType.SingleBanner) {
            Material<ImageInfo> materialBanner = homeDataBean.dataMap.get(ResponseDataTypeAPI.HomeDataType.BANNERS);
            if (materialBanner != null && materialBanner.mList != null){
                Map<String, String> hashMap = new HashMap<>();
                hashMap.put("position",
                        String.valueOf(position));
                DateUtil.setCityUMeng(hashMap, UMengConstants.NEW_HOME_SESSIONBANNER);
                Intent intent = new Intent(getContext(), WebViewActivity.class);
                intent.putExtra(WebViewActivity.EXTRA_URL,
                        materialBanner.mList.get(position).url);
                intent.putExtra(WebViewActivity.STORE_ID,
                        homeDataBean == null ? "" : homeDataBean.id);
                startActivity(intent);
            }
        }
        if (type == Constants.HeadViewType.SetHeadLine) {
            Material<HeadInfo> materialHeadInfo = homeDataBean.dataMap.get(ResponseDataTypeAPI.HomeDataType.SETHEADLINE);
            if (materialHeadInfo != null && materialHeadInfo.mList != null){
                Map<String, String> hashMap = new HashMap<>();
                hashMap.put("position",
                        String.valueOf(position));
                DateUtil.setCityUMeng(hashMap, UMengConstants.NEW_HOME_SETHEADLINE);

                DateUtil.setCityUMeng(hashMap, UMengConstants.NEW_HOME_YIMIREPORT_BTN);

                Intent intent = new Intent(getContext(), WebViewActivity.class);
                intent.putExtra(WebViewActivity.EXTRA_URL,
                        materialHeadInfo.mList.get(position).url);
                intent.putExtra(WebViewActivity.STORE_ID,
                        homeDataBean == null ? "" : homeDataBean.id);
                startActivityForResult(intent, 2000);
            }
        }
    }

    @Override
    public void fetchDataFromNetwork(String key) {
        initRequestAPI(key);
    }
    @Override
    public void initRequestAPI(String requestKeys) {
        if(requestKeys != null && CartUpdateAPI.CART_UPDATE_API.equals(requestKeys) && mCartUpdateAPI == null) {
            initCartUpdateAPI();
        }

        if (requestKeys != null && GetRedPointAPI.GETREDURL.equals(requestKeys)) {
            String token = mDataManager.get(CacheKeys.TOKEN);
            if (StringUtils.isEmpty(token))
                return;
            mGetRedPointAPI = new GetRedPointAPI(token, this);
            mGetRedPointAPI.getRedPoint();
        }
        // 清除小红点
        if (requestKeys != null && requestKeys.equals(ClearRedPointAPI.CLEARURL)) {
            mClearRedPointAPI = new ClearRedPointAPI(DataManager.getInstance()
                    .<String>get(CacheKeys.TOKEN), Constants.RedPointType.BOUNS, this);
        }
        if (requestKeys != null && HomeDataAPI.HOMEDATAURL.equals(requestKeys)){
            if (mCurrentAddress == null) return;
            if (mCurrentAddress instanceof ShortAddress){
                mHomeDataAPI = new HomeDataAPI(mCurrentAddress.longitude, mCurrentAddress.latitude,
                        mCurrentAddress.poiId, Constants.BAIDU_COORD_SYSTEM, this);
                mHomeDataAPI.getHomeDataByLocated();
            }else{
                mHomeDataAPI = new HomeDataAPI(String.valueOf(mCurrentAddress.id), this);
                mHomeDataAPI.getHomeDataBySaved();
            }
        }
    }

    /**
     * 同步购物车数据
     */
    private void flushCartData() {
        if(isNeedGetCart && DataManager.getInstance().get(CacheKeys.TOKEN) != null) {
            getCartData();
            isNeedGetCart = false;
        }
    }
    /**
     * 获取购物车数据
     */
    private void getCartData() {
        fetchUpdateCartData();
        if(getActivity() != null) {
            showPopupWindow(getActivity(), R.id.popupwindow_container);
        }
        if (mCartUpdateAPI != null) {
            mCartUpdateAPI.getCartInfo();
        }
    }
    //清除小红点
    public void clearBonusRedPoint(){
        fetchData(true, mClearRedPointAPI.CLEARURL);
        if (mClearRedPointAPI != null) {
            mClearRedPointAPI.toClearRedPoint();
        }
    }
    HomeAdDialog dialog = null;
    public void createAndShowDialog(boolean isShow){
        if (!isAdded() && dialog != null) return;
        if (isShow) {
//            dialog.show();
            UiUtils.showAlertDialog(dialog);
        }
        else {
            dialog.dismiss();
        }
    }

    public Target mTarget = new Target() {
        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            showHomeAdImage(bitmap);
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {
            dialog.dismiss();
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
        }
    };

    private boolean canPullMessageShow;
    //显示首页蒙层图片
    public void showHomeAd(boolean isShow){
        if (!isAdded()) return;
        if (((YMXMainActivity)getActivity()).mGuideLayout.getVisibility() == View.VISIBLE) return;
        if (homeDataBean == null || homeDataBean.mHomeAdWindow == null) return;
        if (dialog == null)
            dialog = new HomeAdDialog(getActivity(), homeDataBean);
        if (!isShow){
            dialog.hide();
            return;
        }
        String url = homeDataBean.mHomeAdWindow.image;
        if (UiUtils.isShowHomeAd(getActivity(), url)){
            dialog.imageView.setTag(mTarget);
            if(pullMessage!=null)dialog.setOnImgCancelListener(new HomeAdDialog.OnImgCancelListener() {
                @Override
                public void onCanceled() {
                    dealPullMessage(pullMessage);
                }
                @Override
                public void onClicked() {
                    canPullMessageShow = true;
                }
            });
            Picasso.with(getActivity()).load(DataManager.getInstance().
                    getImageUrl(url, DeviceUtils.getScreenWidth(getActivity()) / 2)).into(mTarget);
        }else if(!mIsPullMessageChecked) {
            canPullMessageShow = false;
            if(pullMessage!=null){
                dealPullMessage(pullMessage);
            }else{
                checkAndDealPullMessage();
            }
        }
    }

    public void showHomeAdImage(Bitmap bitmap){
        if (bitmap == null || getActivity() == null) return;
        if (((YMXMainActivity) getActivity()).mSessionFragment != null) {
            createAndShowDialog(false);
        } else {
            SharedPreferencesHelper.commitLong("ad_home_time", System.currentTimeMillis());
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            float scale = (float)width / height;
            dialog.imageView.setLayoutParams(dialog.relImage, scale);
            dialog.imageView.setImageBitmap(bitmap);
            createAndShowDialog(true);
        }
    }
    @Override
    public void onHttpSuccess(String url, JSONObject responseJson) {
        if (layout != null) layout.setRefreshing(false);
        if (mGetRedPointAPI != null && url.contains(mGetRedPointAPI.GETREDURL)) {
            // 设置订单tab状态
            SharedPreferencesHelper.commitBoolean(Constants.ISUPDATEORDERTABRPOINT, false);
            List<KV> kvList = mGetRedPointAPI.parseJson(responseJson);
            if (kvList != null) {
                for (KV kv : kvList) {
                    // 订单小红点
                    if (kv.key.equals(Constants.RedPointType.ORDER)) {
                        if (!StringUtils.isEmpty(kv.value)) {
                            EventBus.getDefault()
                                    .post(new OrderListPointTab(Integer.parseInt(kv.value),
                                            Constants.RedPointType.ORDER, false));
                        }
                    }
                    if (kv.key.equals(Constants.RedPointType.BOUNS)) {
                        if (!StringUtils.isEmpty(kv.value)) {
                            EventBus.getDefault()
                                    .post(new OrderListPointTab(Integer.parseInt(kv.value),
                                            Constants.RedPointType.BOUNS, false));
                        }
                    }
                }
            }
        }
        if (mHomeDataAPI != null && url.contains(HomeDataAPI.HOMEDATAURL)){
            homeDataBean = mHomeDataAPI.parseJson(responseJson);
            UiUtils.setLastFlushTime(this);
            if (mContentFrame == null || homeDataBean == null) return;
            Store store = new Store();
            store.id = homeDataBean.id;
            store.name = homeDataBean.name;
            store.regionId = homeDataBean.regionId;
            store.deliveryZoneUrl = homeDataBean.deliveryZoneUrl;
            store.cannotDeliverText = homeDataBean.cannotDeliverText;
            store.isActive = homeDataBean.isActive;
            SharedPreferencesHelper.saveStore(store, SharePreferenceKeys.CURRENT_STORE);
            Address address = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
            if (address != null) {
                address.storeId = String.valueOf(store.id);
                SharedPreferencesHelper.saveAddress(address, SharePreferenceKeys.CURRENT_ADDRESS);
                EventBus.getDefault()
                    .postSticky(
                        new String(
                            Constants.EVENT_BUS_GET_ADDRESS_SUCCESS_MESSAGE));
            }
            mContentFrame.setVisibility(View.VISIBLE);
            if (!homeDataBean.isActive) {
                showCannotDeliverView();
            } else {
                mContentFrame.setVisibility(View.VISIBLE);
                mLoadingView.setVisibility(View.GONE);
                mLocatingFailedView.setVisibility(View.GONE);
                mCannotDeliverView.setVisibility(View.GONE);
            }
            fetchAdInfoData(homeDataBean);
            initViewData(homeDataBean);
//            if(!hasPullMessage())
            showHomeAd(true);
        }

        if (mCartUpdateAPI != null) {
            if(url.contains(mCartUpdateAPI.CART_UPDATE)) {
                CartUpdate cartUpdate = mCartUpdateAPI.parseJson(responseJson);
                CartManager.getInstance().updateCartGoods(cartUpdate, mPlusMinusIcon);
            }
            if(url.contains(CartUpdateAPI.CART_GET)) {
                CartUpdate cartUpdate = mCartUpdateAPI.parseJson(responseJson);
                CartManager.getInstance().updateCartGoods(cartUpdate);
                if(mHomeListViewAdapter != null) {
                    mHomeListViewAdapter.notifyDataSetChanged();
                }
                if(mPlusMinusIconMessage != null && mPlusMinusIconMessage.message.contains("/IsFisrt") && mPlusMinusIconMessage.icon != null ) {
                    mPlusMinusIconMessage.message = mPlusMinusIconMessage.icon.mCurrentButtonState;
                    if(mPlusMinusIconMessage != null && mPlusMinusIconMessage.icon != null && mPlusMinusIconMessage.icon.mGoodsItem != null) {
                        if(mCurrentGoodsItemId == mPlusMinusIconMessage.icon.mGoodsItem.id) {
                            EventBus.getDefault().post(mPlusMinusIconMessage);
                        }
                    }
                    EventBus.getDefault().removeStickyEvent(mPlusMinusIconMessage);
                }
            }
            if(mPlusMinusIcon != null) {
                mPlusMinusIcon.setButtonCanClick(true);
            }
            UiUtils.updateCartDescription(getActivity(), Constants.PageType.HOME);
        }
        hidePopupWindow();
        hideDialog();
    }

    @Override
    public void getRawResponse(String url, Response response) {
        super.getRawResponse(url, response);
        ServiceUtils.setTime(response);
    }

    void initViewData(HomeDataBean homeDataBean){
        if (DataManager.getInstance().get(CacheKeys.TOKEN) != null) flushCartData();
        headView.removeAllViews();
        headView.bindData(homeDataBean);
        if (mHomeDataAPI != null){
            ServiceUtils.infilterServiceData(getActivity(), mHomeDataAPI.mList,
                    Constants.ServicePageType.HOMEFRAGMENT);

            if (text_marquee_hight != null) text_marquee_hight.stopScroll();
            if (!StringUtils.isEmpty(homeDataBean.storeNotice)){
                if (UiUtils.isNeedNotice(String.valueOf(homeDataBean.id))){
                    linMarquee.setVisibility(View.VISIBLE);
                    text_marquee_hight.setText(homeDataBean.storeNotice);
                    float left = getViewWidthForMarquee(marquee_left);
                    float right = getViewWidthForMarquee(deleteImg);
                    text_marquee_hight.init(0, left, right);
                    text_marquee_hight.setTextColor(
                            getResources().getColor(R.color.home_marquee_text));
                    text_marquee_hight.setSpeed(1.5f);
                    text_marquee_hight.startScroll();
//                    textMarquee.setText(homeDataBean.storeNotice);
                }else{
                    linMarquee.setVisibility(View.GONE);
                }
            }else{
                linMarquee.setVisibility(View.GONE);
            }
            mList = mHomeDataAPI.goodsItems;
            mHomeListViewAdapter.setMLastPosition(scrollIndex);
            mHomeListViewAdapter.setList(mHomeDataAPI.goodsItems);
            CartManager.getInstance().setSortSections(mHomeDataAPI.goodsItems);
        }
        if (isAddressChange) {
            isAddressChange = false;
            mPinnedSectionListView.setSelection(0);
        }
    }

    @Override
    public void OnHttpFailure(String url, String errorMessage, boolean errorFromUs) {
        if(mPlusMinusIcon != null) {
            mPlusMinusIcon.setButtonCanClick(true);
        }
        layout.setRefreshing(false);
        hidePopupWindow();
        hideDialog();
    }

    // 地址管理页面 监听到地址改变更新首页内容
    public void onEventMainThread(ShowAdSelectChange event) {
        if (homeDataBean != null){
            SharedPreferencesHelper.commitLong(String.valueOf(homeDataBean.id), 0);
        }

        Address mAddress = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
        if (mAddress != null && isAdded()){
            if(getActivity() instanceof YMXMainActivity) {
                ((YMXMainActivity) getActivity()).setCityName(mAddress.city);
            }
        }
        isNeedGetCart = true;
        isAddressChange = true;
        mSharedPreferences.edit().putBoolean(Constants.IS_LOADING_DATA, true).commit();
        showLoadingView(UiUtils.getSafeActivity(this).getResources()
                .getString(R.string.loading));
        reFreshData();
        EventBus.getDefault().removeStickyEvent(event);
    }

    // 刷新ListView中的数据
    public void onEventMainThread(String message) {
        if (message != null) {
            //刷新购物车
            if ((Constants.EVENT_BUS_PAY_SUC_UPDATE_CART).equals(message)){
                isNeedGetCart = true;
                flushCartData();
                return;
            }
            // 刷新HomeFragment中商品列表
            if ((Constants.EVENT_BUS_HOME_FRAGMENT_REFRESH).equals(message)) {
                if (mHomeListViewAdapter != null) {
                    mHomeListViewAdapter.notifyDataSetChanged();
                }
                EventBus.getDefault().removeStickyEvent(message);
            }
            // 登录成功刷新首页所有数据
            if (Constants.EVENT_BUS_LOGIN_SUCCESS_MESSAGE.equals(message)){
                isAddressChange = true;
                if (getActivity() != null){
                    ((BaseNaviFragmentGroupActivity)getActivity()).clearServiceMapData(null);
                }
                fetchData();
                EventBus.getDefault().removeStickyEvent(message);
            }
        }
    }

    // 发起商品 + / - 的请求
    public void onEventMainThread(PlusMinusIconMessage message) {
        isAddressChange = false;
        if (message != null) {
            //判断是否为没登陆购买
            if(message.message != null && message.message.contains("/IsFisrt") &&
                    message.message.contains(Constants.STATE_HOMENEWFRAGMENT_BUTTON_BROADCAST)) {
                mPlusMinusIconMessage = message;
                //判断第一次来的时候id 和 当刷新后id 是否一致 不一致不添加商品
                if(message.icon != null && message.icon.mGoodsItem != null) {
                    mCurrentGoodsItemId = message.icon.mGoodsItem.id;
                }
                isNeedGetCart = true;
//                reFreshData();
                fetchData();
                return ;
            }
            //正常购买
            mPlusMinusIcon = message.icon;
            if(message.message != null && message.message.equals(Constants.STATE_HOMENEWFRAGMENT_BUTTON_BROADCAST)) {
                dealPlusMinusProtocol();
            }
        }
    }

    @Override
    public void onPlusButtonClick(View plusView, Point point, Bitmap animBack) {

        ImageView mCartView = ((YMXMainActivity) getActivity()).getmCartView();
        PaoWuXianAnimTool.startAnim(getActivity(), plusView, mCartView, animBack, 600, new PaoWuXianAnimator.onPaoWuXianEndListener() {
            @Override
            public void onEnd() {
                if (getActivity() instanceof YMXMainActivity)
                    ((YMXMainActivity) getActivity()).initCartViewAnim(false);
            }
        });


        if(true)
            return;
        
        ParabolaView parabolaView = new ParabolaView(getActivity(), animBack);
        if(mMainFrame != null) {
            mMainFrame.addView(parabolaView);
        }
        parabolaView.setAnimListener(new ParabolaView.AnimListener() {
            @Override
            public void onEndAnim() {
                if (getActivity() instanceof YMXMainActivity)
                    ((YMXMainActivity) getActivity()).initCartViewAnim(false);
            }
        });
        parabolaView.startAnimation(mHandler, SharedPreferencesHelper.getCartViewLocation(), point);
    }

    @Override
    public void isNeedUpdate() {
        if (mHomeListViewAdapter != null) mHomeListViewAdapter.notifyDataSetChanged();
    }

    @Override
    public void isNeedUnbindService() {

    }

    /**
     * 添加速度跟踪事件
     * @param event
     */
    private void addVelocityTracker(MotionEvent event) {
        if (velocityTracker == null) {
            velocityTracker = VelocityTracker.obtain();
        }
        velocityTracker.addMovement(event);
    }

    /**
     * 清除速度追踪
     */
    private void recycleVelocityTracker() {
        if (velocityTracker != null) {
            velocityTracker.recycle();
            velocityTracker = null;
        }
    }

    /**
     * 获得当前速度
     * @return
     */
    private int getScrollVelocity() {
        if (velocityTracker != null) {
            velocityTracker.computeCurrentVelocity(1000);
            return (int) velocityTracker.getXVelocity();
        }
        return 0;
    }
}
